package com.atguigu.jucdemo.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockDemo {
    private Lock lock1 = new ReentrantLock();
    private Lock lock2 = new ReentrantLock();
    public void t1(){
        lock1.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"自己持有A锁，尝试获得B锁");
            TimeUnit.SECONDS.sleep(1);
            lock2.lock();
            try {

            }finally {
                lock2.unlock();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock1.unlock();
        }
    }
    public void t2(){
        lock2.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"自己持有B锁，尝试获得A锁");
            TimeUnit.SECONDS.sleep(1);
            lock1.lock();
            try {

            }finally {
                lock1.unlock();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock2.unlock();
        }
    }

    public static void main(String[] args) {
        DeadLockDemo deadLockDemo = new DeadLockDemo();
        new Thread(()->{deadLockDemo.t1();},"A").start();
        new Thread(()->{deadLockDemo.t2();},"B").start();
    }
}
